<?php

	include(dirname(__FILE__).'/../../config/config.inc.php');
	include(dirname(__FILE__).'/../../header.php');
	include(dirname(__FILE__).'/samanpayment.php');
	//require_once(ROOT.'kernel/classes/component/nusoap/lib/nusoap.php');

	if (!$cookie->isLogged())
		Tools::redirect('authentication.php?back=order.php');
	$samanpayment = new samanpayment();
	$State;  
	$RefNum = -1;
	$ResNum = -1; 
	//$TotalAmount=0;


	if( isset($_POST['State']) )
	{
		$State  = $_POST['State'];
		$RefNum = $_POST['RefNum'];
		$ResNum = $_POST['ResNum'];

		if( ( empty($State) or empty($ResNum) or strlen($RefNum) != 20 ) or $State != 'OK' )
		{
			$samanpayment->checkErrorState($State,$ResNum,$RefNum);
			return false;           
		}
		else
		{
			//search for Ref Num in db => if not exist =>
			//show ok and do verify

			$searchRefNum = $samanpayment->searchRefNum($RefNum);
			$searchResNum = $samanpayment->searchResNum($ResNum);
		
			if( count( $searchResNum ) > 0 ) 
			{
				if( count( $searchRefNum ) > 0 ) // or if( $searchResNum['payment'] > 0) 
				{
					$samanpayment->checkErrorState($State,$ResNum,$RefNum,"Transaction Completed. Go Tracking Order",true);         
					//$this->setMsg( "لطفا به قسمت رهگيري سفارش مراجعه کنيد" );
					return false;
				}
				else if ($searchResNum['payment'] > 0)
				{
					$samanpayment->checkErrorState($State,$ResNum,$RefNum,"Transaction Completed. Go Tracking Order",true);         
					//$this->setMsg( "لطفا به قسمت رهگيري سفارش مراجعه کنيد" );
					return false;
				}
			} 
			else 
			{
				$samanpayment->checkErrorState($State,$ResNum,$RefNum,"Transaction Not Exist",true);         
				//$this->setMsg("همچين تراکنشي در سمت فروشنده تعريف نشده")
				return false;
			}

			//$samanpayment->checkErrorState($State,$ResNum,$RefNum,"result=".$result."; TotalAmount=".$TotalAmount."; Error verify",false);  
			$result = $samanpayment->lastCheck($ResNum,$RefNum);

			if($result)
			{
				$currency = new Currency(intval(isset($_POST['currency_payement']) ? $_POST['currency_payement'] : $cookie->id_currency));
				$total = floatval(number_format($cart->getOrderTotal(true, 3), 2, '.', ''));

				//function validateOrder($id_cart, $id_order_state, $amountPaid, $paymentMethod = 'Unknown', $message = NULL, $extraVars = array(), $currency_special = NULL, $dont_touch_amount = false)

				$samanpayment->validateOrder($cart->id,  _PS_OS_PREPARATION_, $total, $samanpayment->displayName, NULL, NULL, $currency->id);
				//$order = new Order($samanpayment->currentOrder);
				//$samanpayment->writePaymentcarddetails($order->id, $cardholderName, $cardNumber);

				Tools::redirectLink(__PS_BASE_URI__.'order-confirmation.php?id_cart='.$cart->id.'&id_module='.$samanpayment->id.'&id_order='.$samanpayment->currentOrder.'&key='.$order->secure_key);

			}
		}
	}


	include_once(dirname(__FILE__).'/../../footer.php');
?>